package com.leyou.item.web;

import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("spec")
public class SpecController {
    private final SpecGroupService groupService;
    private final SpecParamService paramService;

    public SpecController(SpecGroupService groupService, SpecParamService paramService) {
        this.groupService = groupService;
        this.paramService = paramService;
    }

    /**
     * 根据分类查询规格组
     * @param id 分类id
     * @return 规格组集合
     */
    @GetMapping("/groups/of/category")
    public ResponseEntity<List<SpecGroupDTO>> queryGroupByCategory(@RequestParam("id") Long id){
        List<SpecGroup> list = groupService.query().eq("category_id", id).list();
        return ResponseEntity.ok(SpecGroupDTO.convertEntityList(list));
    }

    /**
     * 根据条件查询规格参数
     * @param cid 分类id
     * @param gid 规格组id
     * @param searching 是否参与搜索
     * @return 参数集合
     */
    @GetMapping("params")
    public ResponseEntity<List<SpecParamDTO>> queryParams(
            @RequestParam(value = "groupId", required = false) Long gid,
            @RequestParam(value = "categoryId", required = false) Long cid,
            @RequestParam(value = "searching", required = false) Boolean searching
    ){
        return ResponseEntity.ok(paramService.queryParams(gid, cid, searching));
    }

    /**
     * 新增规格组
     * @param groupDTO 规格组数据
     * @return 无
     */
    @PostMapping("group")
    public ResponseEntity<Void> saveGroup(@RequestBody SpecGroupDTO groupDTO){
        groupService.save(groupDTO.toEntity(SpecGroup.class));
        // 新增成功，返回201
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    /**
     * 根据分类id查询规格组及组内参数
     * @param id 分类id
     * @return 组及组内参数
     */
    @GetMapping("list")
    public ResponseEntity<List<SpecGroupDTO>> querySpecList(@RequestParam("id") Long id){
        return ResponseEntity.ok(groupService.querySpecList(id));
    }
}
